package cn.xawl.gulimall.product.service.impl;

import cn.xawl.gulimall.product.dao.AttrGroupDao;
import cn.xawl.gulimall.product.dao.SkuSaleAttrValueDao;
import cn.xawl.gulimall.product.entity.SkuImagesEntity;
import cn.xawl.gulimall.product.entity.SpuInfoDescEntity;
import cn.xawl.gulimall.product.service.AttrGroupService;
import cn.xawl.gulimall.product.service.SkuImagesService;
import cn.xawl.gulimall.product.service.SpuInfoDescService;
import cn.xawl.gulimall.product.vo.itemvo.SkuItemVo;
import cn.xawl.gulimall.product.vo.itemvo.SkuItemsSaleAttrVo;
import cn.xawl.gulimall.product.vo.itemvo.SpuItemAttrGroupVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.xawl.common.utils.PageUtils;
import cn.xawl.common.utils.Query;

import cn.xawl.gulimall.product.dao.SkuInfoDao;
import cn.xawl.gulimall.product.entity.SkuInfoEntity;
import cn.xawl.gulimall.product.service.SkuInfoService;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private SkuSaleAttrValueDao skuSaleAttrValueDao;

    @Autowired
    private ThreadPoolExecutor threadPool;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();

        /*
        key: '华为',//检索关键字
        catalogId: 0,
        brandId: 0,
        min: 0,
        max: 0
         */

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(w -> {
                w.eq("sku_id", key).or().like("sku_name", key);
            });
        }
        //取出参数中的分类id
        String catalogId = (String) params.get("catalogId");
        if (StringUtils.isNotBlank(catalogId) && Integer.parseInt(catalogId) > 0) {
            wrapper.eq("catalog_id", catalogId);
        }

        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotBlank(brandId) && Integer.parseInt(brandId) > 0) {
            wrapper.eq("brand_id", brandId);
        }

        /*
         * 价格区间
         */
        String min = (String) params.get("min");
        if (StringUtils.isNotEmpty(min)) {
            BigDecimal bigDecimal = new BigDecimal(Integer.parseInt(min));
            if (bigDecimal.compareTo(new BigDecimal(0)) > 0) {
                //gt 大于  ge：大于等于
                wrapper.ge("price", min);
            }
        }
        String max = (String) params.get("min");
        if (StringUtils.isNotEmpty(max)) {
            BigDecimal bigDecimal = new BigDecimal(Integer.parseInt(max));
            if (bigDecimal.compareTo(new BigDecimal(0)) > 0) {
                //gt 大于  ge：大于等于
                wrapper.ge("price", min);
            }
        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public SkuItemVo buildItemInfo(Long skuId) {
        SkuItemVo itemInfo = new SkuItemVo();

        CompletableFuture<SkuInfoEntity> skuInfoFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity skuInfo = this.getById(skuId);
            //sku的基本信息
            itemInfo.setSkuInfo(skuInfo);
            return skuInfo;
        }, threadPool);

        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            //sku的图片信息
            List<SkuImagesEntity> skuImages = skuImagesService.list(new QueryWrapper<SkuImagesEntity>().eq("sku_id", skuId));
            itemInfo.setSkuImages(skuImages);
        }, threadPool);

        CompletableFuture<Void> descFuture = skuInfoFuture.thenAcceptAsync(info -> {
            //spu的描述信息（图片）
            SpuInfoDescEntity spuDesc = spuInfoDescService.getById(info.getSpuId());
            itemInfo.setSpuInfoDesc(spuDesc);
        }, threadPool);


        CompletableFuture<Void> groupAttrFuture = skuInfoFuture.thenAcceptAsync(info -> {
            //分组属性信息
            List<SpuItemAttrGroupVo> attrGroups = attrGroupDao.getGroupAttrsBySpuIdAndCatalogId(info.getSpuId(), info.getCatalogId());
            itemInfo.setGroupAttrs(attrGroups);
        }, threadPool);


        CompletableFuture<Void> saleAttrFuture = skuInfoFuture.thenAcceptAsync(info -> {
            //sku销售属性
            List<SkuItemsSaleAttrVo> skuSaleAttrs = skuSaleAttrValueDao.getSaleAttrsBySpuId(info.getSpuId());
            System.out.println("=========" + skuSaleAttrs);
            itemInfo.setSaleAttrs(skuSaleAttrs);
        }, threadPool);

        try {
            CompletableFuture<Void> allOf = CompletableFuture.allOf(imageFuture, descFuture, groupAttrFuture, saleAttrFuture);
            allOf.get(); //阻塞等待全部异步任务完成
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }


        return itemInfo;
    }

}